const fs = require("fs"),
    {getDirectoryName,gm3u8} = require("./common"),
    request = require('request'),
    {getAllFile,emptyDir} = require('../../common/file'),
    {putFile} = require('../../common/oss'),
    path  = require('path')

function diskToHLS (ctx){
    const query = ctx.query
    //判断是OSS还是本地
    let domain = ""
    if (global.config.oss.status){
        domain = global.config.oss.domain //OSS地址
    }else{
        domain = global.config.mediaServer.domain //网络地址
    }

    return new Promise((resolve, reject) => {
        fs.exists(query.uri, function(exists){
            if (!exists){ //文件不存在
                reject({
                    msg:"硬盘文件不存在",
                    code:"40503"
                })
            }else{
                let filesArr = getDirectoryName()
                //1 - 创建目录
                fs.mkdirSync(filesArr.file,{
                    recursive: true
                })

                //2 - 复制文件
                fs.copyFileSync(query.uri, filesArr.file + filesArr.fileName + '.mp4')

                //3- 判断是否生成封面文件
                let cover = []
                let coverImage = []
                if (query.cover !== ''){
                    let coverArray = query.cover.split(',')
                    for (let i in coverArray){
                        let filename = parseInt(Math.random()*(999999999+100000000),10) + '.jpg'
                        let coverFileName = domain + filesArr.rfile + filename
                        cover.push(coverFileName)

                        let localName = filesArr.file + filename
                        coverImage.push({
                            filePath:filesArr.file + filesArr.fileName + '.mp4',
                            savePath:localName,
                            second:coverArray[i]
                        })
                    }
                }

                //4 - 异步生成

                //建立全局任务线
                global.task[filesArr.fileName]={
                        "liveAddress" : false,
                        "hdAddress" : false,
                        "coverCount":coverImage.length
                }
                //定时查看任务状态
                let ossTimer = setInterval( async ()=>{
                    if (global.task[filesArr.fileName].hdAddress && global.task[filesArr.fileName].liveAddress && global.task[filesArr.fileName].coverCount === 0){
                        console.log(colors(['green'], '[√]HLS任务全部转换完成'))
                        delete global.task[filesArr.fileName]
                        //如果开启OSS，则上传OSS
                        if(global.config.oss.status){
                            let fileList = getAllFile(filesArr.file)
                            for(let i in fileList){
                                let result = await putFile(filesArr.rfile + path.basename(fileList[i]), fileList[i])
                                if (result){
                                    console.log(colors(['green'], '[√]已经上传',fileList[i]))
                                    global.log('OSS文件上传',fileList[i])
                                }else{
                                    console.log(colors(['red'], '[×]上传失败', fileList[i]))
                                    global.log('OSS上传失败',fileList[i])
                                }
                            }
                            //删除本地
                            emptyDir(filesArr.file)
                        }

                        //执行回调
                        let callback = query.callback
                        let connector = callback.indexOf("?") === -1 ? "?" : "&" //判断回调地址是否存在传参
                        request(callback + connector + "status=1&t=" + Date.parse(new Date()))
                        clearInterval(ossTimer);
                    }
                },5000)

                //生成流畅hls
                gm3u8(
                    global.config.mediaServer.liveAddress,
                    filesArr.file + filesArr.fileName + '.mp4',
                    filesArr.file + filesArr.fileName + '0.m3u8',
                    [],
                    filesArr
                )
                //生成高清hls
                gm3u8(
                    global.config.mediaServer.hdAddress,
                    filesArr.file + filesArr.fileName + '.mp4',
                    filesArr.file + filesArr.fileName + '1.m3u8',
                    coverImage,
                    filesArr
                )



                resolve({
                    liveAddress:domain + filesArr.rfile + filesArr.fileName + '0.m3u8',
                    hdAddress:domain + filesArr.rfile + filesArr.fileName + '1.m3u8',
                    cover:cover
                })
            }
        })
    })
}


module.exports = diskToHLS
